package com.uzai.console.service.zombiefan.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.friendrequest.DeleteUserDto;
import com.uzai.console.dto.zombiefan.zombiefan.ZombieFanIdDto;
import com.uzai.console.dto.zombiefan.zombiefan.ZombieFanIdListDto;
import com.uzai.console.dto.zombiefan.zombiefan.ZombieFanQuery;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.DeviceType;
import com.uzai.console.entity.ZombieFan;
import com.uzai.console.entity.ZombieFanTask;
import com.uzai.console.mapper.WechatUserMapper;
import com.uzai.console.mapper.WxworkUserMapper;
import com.uzai.console.mapper.ZombieFanMapper;
import com.uzai.console.mapper.ZombieFanTaskMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.zombiefan.ZombieFanService;
import com.uzai.console.vo.zombiefan.zombiefan.ZombieFanVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 清理僵尸粉任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class ZombieFanServiceImpl implements ZombieFanService {

    Logger logger = LoggerFactory.getLogger(ZombieFanServiceImpl.class);

    @Autowired
    private ZombieFanMapper zombieFanMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UserService userService;
    @Autowired
    private ZombieFanTaskMapper zombieFanTaskMapper;

    /**
     * 查询清理僵尸粉任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param zombieFanQuery
     * @return null
     */
    public Page<ZombieFanVo> findZombieFanList(ZombieFanQuery zombieFanQuery){

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<ZombieFanVo> zombieFanInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<ZombieFan> page = new Page<>();
        zombieFanQuery.convert(page);
        List<ZombieFan> zombieFanList = zombieFanMapper.findByList(page, zombieFanQuery);
        if(zombieFanList != null){
            for (ZombieFan zombieFan : zombieFanList){
                ZombieFanVo zombieFanInfoVo = new ZombieFanVo();
                BeanUtils.copyProperties(zombieFan, zombieFanInfoVo);

                //查询群发类型名称
                if(StringUtils.isNotBlank(zombieFan.getDeviceType())){
                    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(zombieFan.getDeviceType());
                    if(deviceTypeEnum != null){
                        zombieFanInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
                    }
                }

                //机器人信息
                if(StringUtils.isNotBlank(zombieFan.getDeviceType())){
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(zombieFan.getDeviceUniqueId(), zombieFan.getDeviceType(), zombieFan.getMerId());
                    if(device != null){
                        zombieFanInfoVo.setDeviceId(device.getDeviceId());
                        zombieFanInfoVo.setDeviceName(device.getDeviceName());
                        zombieFanInfoVo.setDeviceRemark(device.getDeviceRemark());
                    }
                }

                zombieFanInfoVoList.add(zombieFanInfoVo);

            }
        }
        //返回到页面分页对象
        Page<ZombieFanVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(zombieFanInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询清理僵尸粉任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param zombieFanIdDto
     * @return null
     */
    public ZombieFanVo findZombieFan(ZombieFanIdDto zombieFanIdDto){
        //返回到页面的VO对象
        ZombieFanVo zombieFanInfoVo = new ZombieFanVo();

        if(zombieFanIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ZombieFan zombieFan = zombieFanMapper.selectById(zombieFanIdDto.getId(), zombieFanIdDto.getMerId());

        if(zombieFan == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(zombieFan, zombieFanInfoVo);

        //查询群发类型名称
        if(StringUtils.isNotBlank(zombieFan.getDeviceType())){
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(zombieFan.getDeviceType());
            if(deviceTypeEnum != null){
                zombieFanInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
            }
        }

        //机器人信息
        if(StringUtils.isNotBlank(zombieFan.getDeviceType())){
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(zombieFan.getDeviceUniqueId(), zombieFan.getDeviceType(), zombieFan.getMerId());
            if(device != null){
                zombieFanInfoVo.setDeviceId(device.getDeviceId());
                zombieFanInfoVo.setDeviceName(device.getDeviceName());
                zombieFanInfoVo.setDeviceRemark(device.getDeviceRemark());
            }
        }

        return  zombieFanInfoVo;
    }

    /**
     * 批量处理清理僵尸粉任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param zombieFanIdListDto
     * @return null
     */
    public void batchDeleteZombieFan(ZombieFanIdListDto zombieFanIdListDto){
        List<Long> idList = zombieFanIdListDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择僵尸粉");
        }

        ZombieFan zombieFan_first = zombieFanMapper.selectById(zombieFanIdListDto.getIdList().get(0), zombieFanIdListDto.getMerId());
        if(zombieFan_first == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "第一个僵尸粉不存在");
        }
        ZombieFanTask zombieFanTask = zombieFanTaskMapper.selectByDeviceUniqueId(zombieFan_first.getDeviceUniqueId(), zombieFan_first.getMerId());
        if(zombieFanTask == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该僵尸粉的清理任务");
        }

        for (Long id : zombieFanIdListDto.getIdList()) {
            ZombieFan zombieFan = zombieFanMapper.selectById(id, zombieFanIdListDto.getMerId());
            if(zombieFan != null){

                //删除ES记录
                //通过查询运营商其他索引分片获取分片索引
                String esName = EsIndexName.UZAI_WX_CONTACTS;
                String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, zombieFan.getMerId());

                Device device = deviceService.findDeviceInfoByDeviceUniqueId(zombieFan.getDeviceUniqueId(), zombieFan.getDeviceType(), zombieFan.getMerId());
                if(device != null){
                    //删除通讯录
                    String wxContactId = zombieFan.getMerId() + "_" + device.getDeviceId() + "_" + zombieFan.getWxid();
                    elasticsearchUtilGroupMsg.deleteDataById(mechantOtherEsIndexName, wxContactId);

                    //删除会员
                    if(Tools.getInteger(zombieFanTask.getDelUser()).intValue() == 1){ //开启清除0积分0余额的会员
                        User userInfoByWxid = userService.findUserInfoByWxid(zombieFan.getMerId(), zombieFan.getWxid(), zombieFan.getDeviceType());
                        if(userInfoByWxid != null){
                            int integral = Tools.getInteger(userInfoByWxid.getIntegral()).intValue();
                            double balance = Tools.getDouble(userInfoByWxid.getBalance()).doubleValue();
                            if(integral == 0 && balance == 0.00){
                                userService.deleteUserInfoByWxid(zombieFan.getMerId(), zombieFan.getWxid(), zombieFan.getDeviceType());
                            }
                        }
                    }

                    //发送MQ消息
                    MsgDto<DeleteUserDto> msgDto = new MsgDto<>();
                    DeleteUserDto deleteUserDto = new DeleteUserDto();
                    deleteUserDto.setWxid(zombieFan.getWxid());
                    msgDto.setContent(deleteUserDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(device.getRecvmsgType());
                    msgDto.setDeviceUniqueId(device.getId());
                    msgDto.setMerId(zombieFan.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.DELETE_USER.getValue());
                    noticeMsgPushProducerService.deleteUser(msgDto);
                }

                zombieFan.setStatus(1); //已处理
                zombieFanMapper.updateById(zombieFan);
            }
        }
    }
}
